  <template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null : 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="法人行"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 18, offset: 1 }"
              >
                <a-select
                  v-if="this.user.admin"
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  @change="handleInstChange"
                  v-model="queryParams.instId"
                >
                  <a-select-option v-for="r in instIdData" :key="r.label"
                    >{{ r.label }}-{{ r.value }}</a-select-option
                  >
                </a-select>
                <a-input
                  v-if="!this.user.admin"
                  v-model="queryParams.instId"
                  :value="this.user.instId"
                  :disabled="true"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="queryParams.instId != ''">
            <a-col :md="12" :sm="24">
              <a-form-item
                label="角色名称："
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 18, offset: 1 }"
              >
                <a-input v-model="queryParams.roleName" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="创建时间"
                :labelCol="{ span: 4 }"
                :wrapperCol="{ span: 20, offset: 0 }"
              >
                <range-date
                  @change="handleDateChange"
                  ref="createTime"
                ></range-date>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div style="text-align: center" v-show="queryParams.instId != ''">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>
      </a-form>
    </div>
    <div v-show="queryParams.instId != ''">
      <div class="operator">
        <a-button
          v-hasPermission="['role:add']"
          ghost
          type="primary"
          @click="add"
          >新增</a-button
        >
        <!--<a-button v-hasPermission="['role:delete']" @click="batchDelete">删除</a-button>-->
        <a-dropdown v-hasPermission="['role:export']">
          <a-menu slot="overlay">
            <a-menu-item key="export-data" @click="exprotExccel"
              >导出Excel</a-menu-item
            >
          </a-menu>
          <a-button> 更多操作 <a-icon type="down" /> </a-button>
        </a-dropdown>
      </div>
      <!-- 表格区域 -->
      <a-table
        ref="TableInfo"
        :columns="columns"
        :rowKey="(record) => record.id"
        :dataSource="dataSource"
        :pagination="pagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :scroll="{ x: 900 }"
        @change="handleTableChange"
      >
        <template slot="remark" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div style="max-width: 200px">{{ text }}</div>
            </template>
            <p style="width: 200px; margin-bottom: 0">{{ text }}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon
            v-hasPermission="['role:update']"
            type="setting"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="edit(record)"
            title="修改角色"
          ></a-icon>
          &nbsp;
          <a-icon
            type="eye"
            theme="twoTone"
            twoToneColor="#42b983"
            @click="view(record)"
            title="查看"
          ></a-icon>
        </template>
      </a-table>
      <!-- 角色信息查看 -->
      <role-info
        @close="handleRoleInfoClose"
        :roleInfoVisiable="roleInfo.visiable"
        :roleInfoData="roleInfo.data"
        :roleInstId="queryParams.instId"
        :roleCodeData="roleCodeData"
      >
      </role-info>
      <!-- 新增角色 -->
      <role-add
        @close="handleRoleAddClose"
        @success="handleRoleAddSuccess"
        :roleAddVisiable="roleAdd.visiable"
        :roleInstId="queryParams.instId"
        :roleCodeData="roleCodeData"
      >
      </role-add>
      <!-- 修改角色 -->
      <role-edit
        ref="roleEdit"
        :roleInfoData="roleInfo.data"
        @close="handleRoleEditClose"
        @success="handleRoleEditSuccess"
        :roleEditVisiable="roleEdit.visiable"
        :roleInstId="queryParams.instId"
        :roleCodeData="roleCodeData"
      >
      </role-edit>
    </div>
  </a-card>
</template>

<script>
import RangeDate from "@/components/datetime/RangeDate";
import RoleAdd from "./RoleAdd";
import RoleInfo from "./RoleInfo";
import RoleEdit from "./RoleEdit";
import { mapState } from "vuex";

export default {
  name: "Role",
  components: { RangeDate, RoleInfo, RoleAdd, RoleEdit },
  //   components: {RangeDate, RoleAdd},
  data() {
    return {
      advanced: false,
      roleInfo: {
        visiable: false,
        data: {},
      },
      roleAdd: {
        visiable: false,
      },
      roleEdit: {
        visiable: false,
      },
      queryParams: {
        createTimeFrom: "",
        createTimeTo: "",
        instId: "",
      },
      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      selectedRowKeys: [],
      pagination: {
        pageSizeOptions: ["10", "20", "30", "40", "100"],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) =>
          `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`,
      },
      loading: false,
      instIdData: [],
      roleCodeData: [],
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.account.user,
      userRoleList: (state) => state.account.roles,
    }),
    columns() {
      let { sortedInfo } = this;
      sortedInfo = sortedInfo || {};
      let { filteredInfo } = this;
      filteredInfo = filteredInfo || {};
      return [
        {
          title: "角色级别",
          dataIndex: "roleCode",
          width: "150px",
          customRender: (text, row, index) => {
            for (let i = 0; i < this.roleCodeData.length; i++) {
              let title = this.roleCodeData[i];
              if (text === title.label) {
                console.log(title.value);
                return <a-tag> {title.value} </a-tag>;
              }
            }
          },
          filters: () => {
            var filterOjbArr = [];
            for (let i = 0; i < this.roleCodeData.length; i++) {
              let title = this.roleCodeData[i];
              let filterOjb = { text: title.value, value: title.label };
              filterOjbArr.push(filterOjb);
            }
            return filterOjbArr;
            /* 将channelTypeData 转换成以下格式数组
            [
                {text: '按钮', value: '1'},
                {text: '菜单', value: '0'}
            ]*/
          },
          filterMultiple: false,
          filteredValue: filteredInfo.roleCode || null,
          onFilter: (value, record) => record.roleCode.includes(value),
        },
        {
          title: "角色名称",
          dataIndex: "roleName",
        },
        {
          title: "状态",
          dataIndex: "status",
          customRender: (text, row, index) => {
            switch (text) {
              case "Y":
                return <a-tag color="cyan"> 启用 </a-tag>;
              case "N":
                return <a-tag color="pink"> 停用 </a-tag>;
              default:
                return text;
            }
          },
          filters: [
            { text: "启用", value: "Y" },
            { text: "停用", value: "N" },
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.status || null,
          onFilter: (value, record) => record.status.includes(value),
        },
        {
          title: "描述",
          dataIndex: "roleDesc",
          scopedSlots: { customRender: "roleDesc" },
          width: 350,
        },
        {
          title: "法人行",
          dataIndex: "instId",

          filterMultiple: false,
          filteredValue: filteredInfo.roleCode || null,
          onFilter: (value, record) => record.roleCode.includes(value),
        },
        /*{
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order
      }, {
        title: '修改时间',
        dataIndex: 'lastUpdateTime',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'modifyTime' && sortedInfo.order
      }, */
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ];
    },
  },
  mounted() {
    this.getInstList();
    // this.$get('admin/upmporg/getInstList').then((r) => {
    //   this.instIdData = r.data
    // })
    if (!this.user.admin) {
      this.handleInstChange(this.user.instId);
    }
  },
  methods: {
    async getInstList() {
      const res = await this.$get("admin/upmporg/getInstList");
      this.instIdData = res.data;
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    add() {
      this.roleAdd.visiable = true;
    },
    async handleInstChange(value) {
      this.queryParams.instId = value;
      if (value != "") {
        const res = await this.$get(
          "admin/upmprole/getRoleCode/" + value + "/add"
        );
        this.roleCodeData = res.data;
        this.search();
      }
    },

    handleRoleAddClose() {
      this.roleAdd.visiable = false;
    },
    handleRoleAddSuccess() {
      this.roleAdd.visiable = false;
      this.$message.success("新增角色成功");
      this.search();
    },
    view(record) {
      this.roleInfo.data = record;
      this.roleInfo.visiable = true;
    },
    handleRoleInfoClose() {
      this.roleInfo.visiable = false;
    },
    edit(record) {
      var q = 0;
      for (let i = 0; i < this.userRoleList.length; i++) {
        var role = this.userRoleList[i];

        //运营中心
        if (
          record.roleCode == "ROLE_SUPER_USER" ||
          record.roleCode == "ROLE_SUPER_MAIN" ||
          record.roleCode == "ROLE_SUPER_OPR" ||
          record.roleCode == "ROLE_BANK_ADMIN"
        ) {
          if (role.roleCode == "ROLE_SUPER_USER") {
            q++;
          }
        }
        //总行
        if (
          record.roleCode == "ROLE_BANK_OPR" ||
          record.roleCode == "ROLE_BANK_AUDIT" ||
          record.roleCode == "ROLE_BIZ_QUERY" ||
          record.roleCode == "ROLE_BRANCH_ADMIN" ||
          record.roleCode == "ROLE_BRANCH_OPR" ||
          record.roleCode == "ROLE_BRANCH_AUDIT" ||
          record.roleCode == "ROLE_SUB_ADMIN" ||
          record.roleCode == "ROLE_SUB_OPR" ||
          record.roleCode == "ROLE_SUB_AUDIT" ||
          record.roleCode == "ROLE_DOT_ADMIN" ||
          record.roleCode == "ROLE_DOT_OPR" ||
          record.roleCode == "ROLE_DOT_AUDIT"
        ) {
          if (role.roleCode == "ROLE_BANK_ADMIN") {
            q++;
          }
        }
        //分行
        if (
          record.roleCode == "ROLE_BRANCH_OPR" ||
          record.roleCode == "ROLE_BRANCH_AUDIT" ||
          record.roleCode == "ROLE_SUB_ADMIN" ||
          record.roleCode == "ROLE_SUB_OPR" ||
          record.roleCode == "ROLE_SUB_AUDIT" ||
          record.roleCode == "ROLE_DOT_ADMIN" ||
          record.roleCode == "ROLE_DOT_OPR" ||
          record.roleCode == "ROLE_DOT_AUDIT"
        ) {
          if (role.roleCode == "ROLE_BRANCH_ADMIN") {
            q++;
          }
        }
        //支行
        if (
          record.roleCode == "ROLE_SUB_OPR" ||
          record.roleCode == "ROLE_SUB_AUDIT" ||
          record.roleCode == "ROLE_DOT_ADMIN" ||
          record.roleCode == "ROLE_DOT_OPR" ||
          record.roleCode == "ROLE_DOT_AUDIT"
        ) {
          if (role.roleCode == "ROLE_SUB_ADMIN") {
            q++;
          }
        }
        //网点
        if (
          record.roleCode == "ROLE_DOT_OPR" ||
          record.roleCode == "ROLE_DOT_AUDIT"
        ) {
          if (role.roleCode == "ROLE_DOT_ADMIN") {
            q++;
          }
        }
      }

      if (q > 0) {
        this.roleInfo.data = record;
        this.roleEdit.visiable = true;
        this.$refs.roleEdit.setFormValues(record);
      } else {
        this.$message.error("没有修改权限");
        return;
      }
    },
    handleRoleEditSuccess() {
      this.roleEdit.visiable = false;
      this.$message.success("修改角色成功");
      this.search();
    },
    handleRoleEditClose() {
      this.roleEdit.visiable = false;
    },
    handleDateChange(value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0];
        this.queryParams.createTimeTo = value[1];
      }
    },
    batchDelete() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning("请选择需要删除的记录");
        return;
      }
      let that = this;
      this.$confirm({
        title: "确定删除所选中的记录?",
        content: "当您点击确定按钮后，这些记录将会被彻底删除",
        centered: true,
        onOk() {
          let roleIds = [];
          let selectedRowKeysStr = "," + that.selectedRowKeys.join(",") + ",";
          roleIds.push(
            that.dataSource
              .filter((f) => {
                return selectedRowKeysStr.indexOf("," + f.roleId + ",") > -1;
              })
              .map((m) => {
                return m.roleId;
              })
          );
          that.$delete("admin/upmprole/" + roleIds.join(",")).then((res) => {
            if (res.data.status) {
              that.$message.success(res.data.message);
              that.selectedRowKeys = [];
              that.search();
            } else {
              that.$message.error(res.data.message);
            }
          });
        },
        onCancel() {
          that.selectedRowKeys = [];
        },
      });
    },
    exprotExccel() {
      let { sortedInfo } = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.$export("admin/upmprole/excel", {
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
      }).then((res) => {
        if (res.data.status) {
          this.$message.success(res.data.message);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    search() {
      let { sortedInfo } = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
      });
    },
    reset() {
      // 取消选中
      this.selectedRowKeys = [];
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent;
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent;
        this.paginationInfo.pageSize = this.pagination.defaultPageSize;
      }
      // 重置列排序规则
      this.sortedInfo = null;
      // 重置查询参数
      this.queryParams = {};
      // 清空时间选择
      this.$refs.createTime.reset();

      if (!this.user.admin) {
        this.handleInstChange(this.user.instId);
      }
    },
    handleTableChange(pagination, filters, sorter) {
      // 将这两个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination;
      this.filteredInfo = filters;
      this.sortedInfo = sorter;
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
      });
    },
    async fetch(params = {}) {
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize;
        params.pageNum = this.pagination.defaultCurrent;
      }
      await this.$get("admin/upmprole", {
        ...params,
      }).then((r) => {
        let data = r.data;
        const pagination = { ...this.pagination };
        pagination.total = data.total;
        this.dataSource = data.rows;
        this.pagination = pagination;
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>
